import time
from voice_module import Control_Voice
import requests
from arm_module import desktopArm

# Flask 服务 API 地址
API_BASE = 'http://172.16.250.167:5000/api/system'

# 定义语音指令映射: 串口收到的命令码 -> 语义动作
voice_mapping = {
    '01': '左转',
    '02': '右转',
    '03': '上移',
    '04': '下移',
    '05': '复位',
    '06': '开始',
    '07': '结束',
    '08': '统计',
    '09': '返回',
    '0A': '合格品数量',
    '0B': '缺陷品数量',
}

# 初始化机械臂和语音控制
arm = desktopArm()
arm.reset_position(times=2000)

# 动作参数配置
move_offset = 50   # 平移距离
lift_height = 200  # 抬臂高度
base_height = 142  # 初始高度

def recv_frame(port, timeout=3.0):
    """
    从串口读取完整一帧：AC <XX> CA
    返回字节串或 None
    """
    buf = b''
    start = time.time()
    # 对齐帧头 0xAC
    while time.time() - start < timeout:
        ch = port.read(1)
        if not ch:
            continue
        if ch == b'\xAC':
            buf = ch
            break
    else:
        return None

    # 读取中间一字节 + 末尾帧尾 0xCA
    needed = 2
    while needed > 0 and time.time() - start < timeout:
        chunk = port.read(needed)
        if not chunk:
            continue
        buf += chunk
        needed -= len(chunk)

    if len(buf) == 3 and buf[2] == 0xCA:
        return buf
    return None


def main():
    print("语音控制监听已启动...")
    try:
        while True:
            frame = recv_frame(Control_Voice.ser)
            if not frame:
                time.sleep(0.1)
                continue

            # 提取命令码
            code = frame[1:2].hex().upper()
            action = voice_mapping.get(code)
            if not action:
                print(f"未识别的命令: {code}")
                continue

            print(f"接收到语音命令: {action} ({code})")

            # 机械臂运动处理
            if action in ['左转', '右转', '上移', '下移', '复位']:
                current = arm.get_point()
                if action == '右转':
                    arm.move_point(x=current.x + move_offset,
                                y=current.y,
                                z=current.z,
                                times=1000)
                elif action == '左转':
                    arm.move_point(x=current.x - move_offset,
                                y=current.y,
                                z=current.z,
                                times=1000)
                elif action == '上移':
                    arm.move_point(x=current.x,
                                y=current.y,
                                z=current.z + move_offset,
                                times=1000)
                elif action == '下移':
                    arm.move_point(x=current.x,
                                y=current.y,
                                z=current.z - move_offset,
                                times=1000)
                elif action == '复位':
                    arm.reset_position(times=2000)
                continue

            # 根据语义动作调用后台 API
            try:
                if action == '开始':
                    resp = requests.post(f"{API_BASE}/start", timeout=1)
                    if resp.ok and resp.json().get('success'):
                        print('>>> 语音触发：系统启动成功')
                    else:
                        print(f'>>> 语音触发启动失败: {resp.text}')
                elif action == '结束':
                    resp = requests.post(f"{API_BASE}/stop", timeout=1)
                    if resp.ok and resp.json().get('success'):
                        print('>>> 语音触发：系统停止成功')
                    else:
                        print(f'>>> 语音触发停止失败: {resp.text}')
                elif action == '统计':
                    # 触发后端广播 nav_stats
                    resp = requests.post(f"{API_BASE}/navigate", json={'action':'stats'}, timeout=1)
                    print('>>> 语音导航到统计页:', resp.ok)

                elif action == '返回':
                    # 触发后端广播 nav_home
                    resp = requests.post(f"{API_BASE}/navigate", json={'action':'home'}, timeout=1)
                    print('>>> 语音导航到主页:', resp.ok)
                elif action == '合格品数量':
                    Control_Voice.send(7, 8)
                elif action == '缺陷品数量':
                    Control_Voice.send(8, 0)
                else:
                    # 保留其他动作处理逻辑，如上下左右
                    print(f'>>> 语音动作 {action} 暂未集成页面控制')
            except Exception as e:
                print(f'>>> 调用后台 API 异常: {e}')

    except KeyboardInterrupt:
        print("语音控制监听中断，退出。")
        Control_Voice.close()


if __name__ == '__main__':
    main()
